package com.fansl.allround.auth.service;

import com.fansl.allround.auth.dto.ClientDTO;
import com.fansl.allround.auth.mapper.OauthClientDetailsMapper;
import com.fansl.allround.auth.model.OauthClientDetails;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.NullArgumentException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author fansl
 * @Description: TODO
 * @date 2019/10/30 14:20
 */
@Service
@Slf4j
public class AllroundClientDetailsService implements ClientDetailsService {
    @Resource
    private OauthClientDetailsMapper oauthClientDetailsMapper;

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        if (clientId == null || clientId.trim().length() <= 0) {
            log.error(" clientId 为空");
            throw new NullArgumentException("clientId 为空");
        }

        OauthClientDetails clients = oauthClientDetailsMapper.selectById(clientId);
        if (clients != null) {
            clients.setClientSecret("{noop}" + clients.getClientSecret());
            return clients;
        }
        throw new NoSuchClientException("No client with requested id: " + clientId);
    }

    public OauthClientDetails insert(ClientDTO clientDTO) {
        OauthClientDetails clientDetails = new OauthClientDetails();
        clientDetails.setClientId(clientDTO.getClientId());
        clientDetails.setClientSecret(clientDTO.getClientSecret());
        clientDetails.setScope(clientDTO.getScope());
        clientDetails.setAuthorizedGrantTypes(clientDTO.getAuthorizedGrantTypes());
        oauthClientDetailsMapper.insert(clientDetails);
        return clientDetails;
    }
}
